//+------------------------------------------------------------------+
//|                                 Ilan-TrioKS v1.45 Professional |
//|                                 三合一智能交易系统 - 专业版      |
//|                                                               KS |
//|                                     http://BigGame24.tripod.com/ |
//+------------------------------------------------------------------+
#property copyright "KS"
#property link      "http://BigGame24.tripod.com/"
#property version   "1.45"
#property description "三合一智能交易系统：集成HiLo RSI、基础Ilan和高级Ilan策略"
#property description "1. HiLo RSI策略：基于RSI指标和高低点突破"
#property description "2. 基础Ilan策略：基于价格突破的马丁格尔系统"
#property description "3. 高级Ilan策略：带RSI过滤的增强版马丁格尔系统"

//+------------------------------------------------------------------+
//| 必要的MQ5头文件导入                                                 |
//+------------------------------------------------------------------+
#include <Trade\Trade.mqh>
#include <Trade\PositionInfo.mqh>
#include <Trade\OrderInfo.mqh>

//+------------------------------------------------------------------+
//| 全局交易对象实例                                                   |
//+------------------------------------------------------------------+
CTrade globalTrade;                    // 全局交易执行对象
CPositionInfo globalPosition;          // 全局持仓信息对象
COrderInfo globalOrder;                // 全局订单信息对象

//+------------------------------------------------------------------+
//| 系统常量定义                                                      |
//+------------------------------------------------------------------+
#define MAX_RETRY_COUNT 100           // 最大重试次数
#define RETRY_DELAY_MS 5000           // 重试延迟(毫秒)
#define DEFAULT_TIMEOUT_HOURS 48.0    // 默认超时时间(小时)
#define MIN_BALANCE_FOR_MM 200000     // 资金管理最小余额
#define MM_COEFFICIENT 0.00001        // 资金管理系数

//+------------------------------------------------------------------+
//| 策略魔法数字定义                                                   |
//+------------------------------------------------------------------+
#define MAGIC_HILO_RSI 10278         // HiLo RSI策略魔法数字
#define MAGIC_BASIC_ILAN 22324       // 基础Ilan策略魔法数字  
#define MAGIC_ADVANCED_ILAN 23794    // 高级Ilan策略魔法数字

//+------------------------------------------------------------------+
//| 颜色常量定义                                                      |
//+------------------------------------------------------------------+
#define COLOR_BUY_SIGNAL clrLime      // 买入信号颜色
#define COLOR_SELL_SIGNAL clrHotPink  // 卖出信号颜色
#define COLOR_PANEL_TEXT clrGray      // 面板文字颜色
#define COLOR_BALANCE_DISPLAY clrDodgerBlue  // 余额显示颜色

//+------------------------------------------------------------------+
//| 基础系统参数设置                                                   |
//+------------------------------------------------------------------+
input group "=== 基础系统参数 ==="
input double    BaseLotSize = 0.01;           // 基础手数
input double    LotMultiplier = 1.55;         // 马丁格尔倍数
input int       LotDecimalPlaces = 2;         // 手数小数位数
input double    GridStepPoints = 30.0;        // 网格间距(点数)
input double    MaxLotSize = 100.0;           // 最大手数限制
input bool      UseMoneyManagement = false;   // 启用资金管理
input double    TakeProfitPoints = 100.0;     // 止盈点数
input bool      UseEquityStop = false;        // 启用净值止损
input double    EquityRiskPercent = 20.0;     // 净值风险百分比
input bool      UseTrailingStop = false;      // 启用追踪止损
input double    TrailingStartPoints = 13.0;   // 追踪止损启动点数
input double    TrailingStepPoints = 3.0;     // 追踪止损步长
input double    SlippagePoints = 5.0;         // 滑点设置

//+------------------------------------------------------------------+
//| HiLo RSI策略参数设置                                              |
//+------------------------------------------------------------------+
input group "=== HiLo RSI策略参数  ==="
input int       HiloMaxPositions = 10;        // 最大持仓数量
input bool      HiloUseTimeout = false;       // 启用超时平仓
input double    HiloTimeoutHours = 48.0;      // 超时时间(小时)
input double    HiloStopLossPoints = 40.0;    // 止损点数

//+------------------------------------------------------------------+
//| 基础Ilan策略参数设置                                              |
//+------------------------------------------------------------------+
input group "=== 基础Ilan策略参数 ==="
input int       BasicIlanMaxPositions = 10;   // 最大持仓数量
input int       BasicIlanTimeframe = 60;      // 开仓时间框架(分钟)

//+------------------------------------------------------------------+
//| 高级Ilan策略参数设置                                              |
//+------------------------------------------------------------------+
input group "=== 高级Ilan策略参数 ==="
input int       AdvancedIlanMaxPositions = 10; // 最大持仓数量
input int       AdvancedIlanTimeframe = 1;     // 开仓时间框架(分钟)

//+------------------------------------------------------------------+
//| HiLo RSI策略数据结构                                              |
//+------------------------------------------------------------------+
struct HiloRsiStrategy
{
   double         lotSize;                     // 当前手数
   double         lotMultiplier;               // 手数倍数
   int            lotDecimalPlaces;            // 手数小数位数
   double         takeProfitPoints;            // 止盈点数
   double         stopLossPoints;              // 止损点数
   double         gridStepPoints;              // 网格间距
   double         slippagePoints;              // 滑点
   bool           isLongTrade;                 // 当前为多头交易
   bool           isShortTrade;                // 当前为空头交易
   bool           shouldTradeNow;              // 是否应该交易
   bool           newOrdersPlaced;             // 是否有新订单
   double         lastBuyPrice;                // 最后买入价
   double         lastSellPrice;               // 最后卖出价
   double         averagePrice;                // 平均价格
   double         priceTarget;                 // 目标价格
   double         buyTarget;                   // 买入目标
   double         sellTarget;                  // 卖出目标
   int            positionCount;               // 持仓数量
   int            tradeNumber;                 // 交易编号
   datetime       lastBarTime;                 // 上一根K线时间
   datetime       orderExpiration;             // 订单过期时间
   double         startEquity;                 // 开始净值
   double         equityHighAmount;            // 净值最高点
   double         previousEquity;              // 上一个净值
   ulong          lastTicket;                  // 最后订单号
   double         currentLotSize;              // 当前手数
   double         spreadValue;                 // 点差值
};

//+------------------------------------------------------------------+
//| 基础Ilan策略数据结构                                              |
//+------------------------------------------------------------------+
struct BasicIlanStrategy
{
   double         lotSize;                     // 当前手数
   double         lotMultiplier;               // 手数倍数
   int            lotDecimalPlaces;            // 手数小数位数
   double         takeProfitPoints;            // 止盈点数
   double         stopLossPoints;              // 止损点数
   double         gridStepPoints;              // 网格间距
   double         slippagePoints;              // 滑点
   int            openTimeframe;               // 开仓时间框架
   bool           isLongTrade;                 // 当前为多头交易
   bool           isShortTrade;                // 当前为空头交易
   bool           shouldTradeNow;              // 是否应该交易
   bool           newOrdersPlaced;             // 是否有新订单
   bool           flagActive;                  // 标志位激活
   double         lastBuyPrice;                // 最后买入价
   double         lastSellPrice;               // 最后卖出价
   double         averagePrice;                // 平均价格
   double         priceTarget;                 // 目标价格
   double         currentBid;                  // 当前买价
   double         currentAsk;                  // 当前卖价
   double         spreadValue;                 // 点差值
   int            positionCount;               // 持仓数量
   int            tradeNumber;                 // 交易编号
   datetime       lastBarTime;                 // 上一根K线时间
   datetime       orderExpiration;             // 订单过期时间
   double         startEquity;                 // 开始净值
   double         equityHighAmount;            // 净值最高点
   double         previousEquity;              // 上一个净值
   ulong          lastTicket;                  // 最后订单号
   double         currentLotSize;              // 当前手数
   double         stopperValue;                // 止损值
};

//+------------------------------------------------------------------+
//| 高级Ilan策略数据结构                                              |
//+------------------------------------------------------------------+
struct AdvancedIlanStrategy
{
   double         lotSize;                     // 当前手数
   double         lotMultiplier;               // 手数倍数
   int            lotDecimalPlaces;            // 手数小数位数
   double         takeProfitPoints;            // 止盈点数
   double         stopLossPoints;              // 止损点数
   double         gridStepPoints;              // 网格间距
   double         slippagePoints;              // 滑点
   int            openTimeframe;               // 开仓时间框架
   bool           isLongTrade;                 // 当前为多头交易
   bool           isShortTrade;                // 当前为空头交易
   bool           shouldTradeNow;              // 是否应该交易
   bool           newOrdersPlaced;             // 是否有新订单
   bool           flagActive;                  // 标志位激活
   double         lastBuyPrice;                // 最后买入价
   double         lastSellPrice;               // 最后卖出价
   double         averagePrice;                // 平均价格
   double         priceTarget;                 // 目标价格
   double         currentBid;                  // 当前买价
   double         currentAsk;                  // 当前卖价
   double         spreadValue;                 // 点差值
   int            positionCount;               // 持仓数量
   int            tradeNumber;                 // 交易编号
   datetime       lastBarTime;                 // 上一根K线时间
   datetime       orderExpiration;             // 订单过期时间
   double         startEquity;                 // 开始净值
   double         equityHighAmount;            // 净值最高点
   double         previousEquity;              // 上一个净值
   ulong          lastTicket;                  // 最后订单号
   double         currentLotSize;              // 当前手数
   double         stopperValue;                // 止损值
};

//+------------------------------------------------------------------+
//| 全局策略实例                                                      |
//+------------------------------------------------------------------+
HiloRsiStrategy      hiloStrategy;            // HiLo RSI策略实例
BasicIlanStrategy    basicStrategy;           // 基础Ilan策略实例
AdvancedIlanStrategy advancedStrategy;        // 高级Ilan策略实例

//+------------------------------------------------------------------+
//| 技术指标面板相关变量                                               |
//+------------------------------------------------------------------+
int indicatorTimeframes[] = {PERIOD_M1, PERIOD_M5, PERIOD_M15, PERIOD_M30, PERIOD_H1, PERIOD_H4, PERIOD_D1};
bool showTechnicalPanel = true;
bool showPriceDisplay = true;
bool showAccountInfo = true;

// MACD指标参数
int macdFastPeriod = 8;
int macdSlowPeriod = 17;
int macdSignalPeriod = 9;
int macdAppliedPrice = PRICE_CLOSE;

// RSI指标参数
int rsiPeriod = 9;
int rsiAppliedPrice = PRICE_CLOSE;

// CCI指标参数
int cciPeriod = 13;
int cciAppliedPrice = PRICE_CLOSE;

// 随机指标参数
int stochKPeriod = 5;
int stochDPeriod = 3;
int stochSlowing = 3;
ENUM_MA_METHOD stochMethod = MODE_EMA;

// 移动平均线参数
int maFastPeriod = 5;
int maSlowPeriod = 9;
ENUM_MA_METHOD maMethod = MODE_EMA;
ENUM_APPLIED_PRICE maAppliedPrice = PRICE_CLOSE;

//+------------------------------------------------------------------+
//| 账户余额和净值显示变量                                             |
//+------------------------------------------------------------------+
double accountBalance;
double accountEquity;
color equityColor = clrForestGreen;
string balanceText = "";
string equityText = "";

//+------------------------------------------------------------------+
//| 技术指标句柄和数据缓冲区                                            |
//+------------------------------------------------------------------+
int rsiHandle;                         // RSI指标句柄
double rsiBuffer[];                    // RSI数据缓冲区

// 多时间框架技术指标句柄
int macdHandles[7];                    // MACD指标句柄数组
int rsiHandles[7];                     // RSI指标句柄数组
int cciHandles[7];                     // CCI指标句柄数组
int stochHandles[7];                   // Stochastic指标句柄数组
int maFastHandles[7];                  // 快速MA句柄数组
int maSlowHandles[7];                  // 慢速MA句柄数组

// 技术指标数据缓冲区
double macdMainBuffer[];               // MACD主线缓冲区
double macdSignalBuffer[];             // MACD信号线缓冲区
double rsiTempBuffer[];                // RSI临时缓冲区
double cciTempBuffer[];                // CCI临时缓冲区
double stochTempBuffer[];              // Stochastic临时缓冲区
double maFastBuffer[];                 // 快速MA缓冲区
double maSlowBuffer[];                 // 慢速MA缓冲区

//+------------------------------------------------------------------+
//| Expert Advisor初始化函数                                          |
//+------------------------------------------------------------------+
int OnInit()
{
    Print("=== Ilan-TrioKS v1.45 Professional 初始化开始 ===");
    
    // 初始化技术指标句柄
    rsiHandle = iRSI(_Symbol, PERIOD_H1, 14, PRICE_CLOSE);
    if (rsiHandle == INVALID_HANDLE)
    {
        Print("错误：无法创建RSI指标句柄");
        return(INIT_FAILED);
    }
    
    // 设置数组为时间序列
    ArraySetAsSeries(rsiBuffer, true);
    ArraySetAsSeries(macdMainBuffer, true);
    ArraySetAsSeries(macdSignalBuffer, true);
    ArraySetAsSeries(rsiTempBuffer, true);
    ArraySetAsSeries(cciTempBuffer, true);
    ArraySetAsSeries(stochTempBuffer, true);
    ArraySetAsSeries(maFastBuffer, true);
    ArraySetAsSeries(maSlowBuffer, true);
    
    // 初始化多时间框架技术指标句柄
    ENUM_TIMEFRAMES timeframes[] = {PERIOD_M1, PERIOD_M5, PERIOD_M15, PERIOD_M30, PERIOD_H1, PERIOD_H4, PERIOD_D1};
    
    for (int i = 0; i < 7; i++)
    {
        // 创建MACD句柄
        macdHandles[i] = iMACD(_Symbol, timeframes[i], macdFastPeriod, macdSlowPeriod, macdSignalPeriod, macdAppliedPrice);
        if (macdHandles[i] == INVALID_HANDLE)
        {
            Print("错误：无法创建MACD指标句柄，时间框架：", timeframes[i]);
        }
        
        // 创建RSI句柄
        rsiHandles[i] = iRSI(_Symbol, timeframes[i], rsiPeriod, rsiAppliedPrice);
        if (rsiHandles[i] == INVALID_HANDLE)
        {
            Print("错误：无法创建RSI指标句柄，时间框架：", timeframes[i]);
        }
        
        // 创建CCI句柄
        cciHandles[i] = iCCI(_Symbol, timeframes[i], cciPeriod, cciAppliedPrice);
        if (cciHandles[i] == INVALID_HANDLE)
        {
            Print("错误：无法创建CCI指标句柄，时间框架：", timeframes[i]);
        }
        
        // 创建Stochastic句柄
        stochHandles[i] = iStochastic(_Symbol, timeframes[i], stochKPeriod, stochDPeriod, stochSlowing, stochMethod, 0);
        if (stochHandles[i] == INVALID_HANDLE)
        {
            Print("错误：无法创建Stochastic指标句柄，时间框架：", timeframes[i]);
        }
        
        // 创建快速MA句柄
        maFastHandles[i] = iMA(_Symbol, timeframes[i], maFastPeriod, 0, maMethod, maAppliedPrice);
        if (maFastHandles[i] == INVALID_HANDLE)
        {
            Print("错误：无法创建快速MA指标句柄，时间框架：", timeframes[i]);
        }
        
        // 创建慢速MA句柄
        maSlowHandles[i] = iMA(_Symbol, timeframes[i], maSlowPeriod, 0, maMethod, maAppliedPrice);
        if (maSlowHandles[i] == INVALID_HANDLE)
        {
            Print("错误：无法创建慢速MA指标句柄，时间框架：", timeframes[i]);
        }
    }
    
    // 初始化策略结构
    InitializeStrategies();
    
    // 创建界面元素
    CreateUserInterface();
    
    Print("=== 初始化完成，三个策略已准备就绪 ===");
    return(INIT_SUCCEEDED);
}

//+------------------------------------------------------------------+
//| Expert Advisor反初始化函数                                        |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
    Print("=== Ilan-TrioKS v1.45 Professional 正在关闭 ===");
    
    // 释放指标句柄
    if (rsiHandle != INVALID_HANDLE)
    {
        IndicatorRelease(rsiHandle);
        rsiHandle = INVALID_HANDLE;
    }
    
    // 释放多时间框架技术指标句柄
    for (int i = 0; i < 7; i++)
    {
        if (macdHandles[i] != INVALID_HANDLE)
        {
            IndicatorRelease(macdHandles[i]);
            macdHandles[i] = INVALID_HANDLE;
        }
        
        if (rsiHandles[i] != INVALID_HANDLE)
        {
            IndicatorRelease(rsiHandles[i]);
            rsiHandles[i] = INVALID_HANDLE;
        }
        
        if (cciHandles[i] != INVALID_HANDLE)
        {
            IndicatorRelease(cciHandles[i]);
            cciHandles[i] = INVALID_HANDLE;
        }
        
        if (stochHandles[i] != INVALID_HANDLE)
        {
            IndicatorRelease(stochHandles[i]);
            stochHandles[i] = INVALID_HANDLE;
        }
        
        if (maFastHandles[i] != INVALID_HANDLE)
        {
            IndicatorRelease(maFastHandles[i]);
            maFastHandles[i] = INVALID_HANDLE;
        }
        
        if (maSlowHandles[i] != INVALID_HANDLE)
        {
            IndicatorRelease(maSlowHandles[i]);
            maSlowHandles[i] = INVALID_HANDLE;
        }
    }
    
    // 清理界面元素
    CleanupUserInterface();
    
    // 清理技术指标面板
    CleanupExpiredObjects();
    
    Print("=== 系统已安全关闭 ===");
}

//+------------------------------------------------------------------+
//| Expert Advisor主循环函数                                          |
//+------------------------------------------------------------------+
void OnTick()
{
    // 检查手数限制
    if (BaseLotSize > MaxLotSize) 
    {
        Print("警告：基础手数超过最大限制，已调整为最大手数");
    }
    
    // 更新账户信息显示
    UpdateAccountInfoDisplay();
    
    // 显示技术指标面板
    if (showTechnicalPanel)
        UpdateCompleteTechnicalPanel();
    
    // 执行HiLo RSI策略
    ExecuteHiloRsiStrategy();
    
    // 执行基础Ilan策略
   ExecuteBasicIlanStrategy();
    
    // 执行高级Ilan策略
    ExecuteAdvancedIlanStrategy();
    
    // 更新评论区信息
    UpdateCommentDisplay();
}

//+------------------------------------------------------------------+
//| 初始化所有策略结构                                                 |
//+------------------------------------------------------------------+
void InitializeStrategies()
{
    // 初始化HiLo RSI策略
    hiloStrategy.lotMultiplier = LotMultiplier;
    hiloStrategy.lotDecimalPlaces = LotDecimalPlaces;
    hiloStrategy.takeProfitPoints = TakeProfitPoints;
    hiloStrategy.stopLossPoints = HiloStopLossPoints;
    hiloStrategy.gridStepPoints = GridStepPoints;
    hiloStrategy.slippagePoints = SlippagePoints;
    hiloStrategy.spreadValue = SymbolInfoInteger(_Symbol, SYMBOL_SPREAD) * _Point;
    
    // 初始化基础Ilan策略
    basicStrategy.lotMultiplier = LotMultiplier;
    basicStrategy.lotDecimalPlaces = LotDecimalPlaces;
    basicStrategy.takeProfitPoints = TakeProfitPoints;
    basicStrategy.stopLossPoints = HiloStopLossPoints;
    basicStrategy.gridStepPoints = GridStepPoints;
    basicStrategy.slippagePoints = SlippagePoints;
    basicStrategy.openTimeframe = BasicIlanTimeframe;
    basicStrategy.spreadValue = SymbolInfoInteger(_Symbol, SYMBOL_SPREAD) * _Point;
    
    // 初始化高级Ilan策略
    advancedStrategy.lotMultiplier = LotMultiplier;
    advancedStrategy.lotDecimalPlaces = LotDecimalPlaces;
    advancedStrategy.takeProfitPoints = TakeProfitPoints;
    advancedStrategy.stopLossPoints = HiloStopLossPoints;
    advancedStrategy.gridStepPoints = GridStepPoints;
    advancedStrategy.slippagePoints = SlippagePoints;
    advancedStrategy.openTimeframe = AdvancedIlanTimeframe;
    advancedStrategy.spreadValue = SymbolInfoInteger(_Symbol, SYMBOL_SPREAD) * _Point;
    
    Print("策略结构初始化完成");
}

//+------------------------------------------------------------------+
//| 创建用户界面元素                                                   |
//+------------------------------------------------------------------+
void CreateUserInterface()
{
    // 创建主标题
    ObjectCreate(0, "MainTitle", OBJ_LABEL, 0, 0, 0);
    ObjectSetInteger(0, "MainTitle", OBJPROP_CORNER, CORNER_LEFT_LOWER);
    ObjectSetInteger(0, "MainTitle", OBJPROP_XDISTANCE, 23);
    ObjectSetInteger(0, "MainTitle", OBJPROP_YDISTANCE, 21);
    ObjectSetString(0, "MainTitle", OBJPROP_TEXT, "Ilan-TrioKS v1.45 Professional");
    ObjectSetInteger(0, "MainTitle", OBJPROP_FONTSIZE, 16);
    ObjectSetString(0, "MainTitle", OBJPROP_FONT, "Times New Roman");
    ObjectSetInteger(0, "MainTitle", OBJPROP_COLOR, clrAqua);
    
    // 创建版权信息
    ObjectCreate(0, "Copyright", OBJ_LABEL, 0, 0, 0);
    ObjectSetInteger(0, "Copyright", OBJPROP_CORNER, CORNER_LEFT_LOWER);
    ObjectSetInteger(0, "Copyright", OBJPROP_XDISTANCE, 3);
    ObjectSetInteger(0, "Copyright", OBJPROP_YDISTANCE, 1);
    ObjectSetString(0, "Copyright", OBJPROP_TEXT, "BigGame24.tripod.com");
    ObjectSetInteger(0, "Copyright", OBJPROP_FONTSIZE, 16);
    ObjectSetString(0, "Copyright", OBJPROP_FONT, "Times New Roman");
    ObjectSetInteger(0, "Copyright", OBJPROP_COLOR, clrDeepSkyBlue);
}

//+------------------------------------------------------------------+
//| 清理用户界面元素                                                   |
//+------------------------------------------------------------------+
void CleanupUserInterface()
{
    // 清理主界面元素
    ObjectDelete(0, "MainTitle");
    ObjectDelete(0, "Copyright");
    ObjectDelete(0, "BalanceLabel");
    ObjectDelete(0, "EquityLabel");
    
    // 清理技术指标面板
    ObjectDelete(0, "TechnicalPanel");
    ObjectDelete(0, "MACD_Panel");
    ObjectDelete(0, "RSI_Panel");
    ObjectDelete(0, "Price_Panel");
    
    // 清理所有时间框架标签
    for(int i = 0; i < 7; i++)
    {
        ObjectDelete(0, "TF_" + IntegerToString(i));
        ObjectDelete(0, "MACD_" + IntegerToString(i));
        ObjectDelete(0, "STR_" + IntegerToString(i));
        ObjectDelete(0, "EMA_" + IntegerToString(i));
    }
}

//+------------------------------------------------------------------+
//| 更新账户信息显示                                                   |
//+------------------------------------------------------------------+
void UpdateAccountInfoDisplay()
{
    accountBalance = NormalizeDouble(AccountInfoDouble(ACCOUNT_BALANCE), 2);
    accountEquity = NormalizeDouble(AccountInfoDouble(ACCOUNT_EQUITY), 2);
    
    // 根据净值与余额比例设置颜色
    if (accountEquity >= accountBalance * 5.0 / 6.0) equityColor = clrDodgerBlue;
    else if (accountEquity >= accountBalance * 4.0 / 6.0) equityColor = clrDeepSkyBlue;
    else if (accountEquity >= accountBalance * 3.0 / 6.0) equityColor = clrGold;
    else if (accountEquity >= accountBalance * 2.0 / 6.0) equityColor = clrOrangeRed;
    else if (accountEquity >= accountBalance / 6.0) equityColor = clrCrimson;
    else equityColor = clrRed;
    
    // 更新余额显示
    ObjectDelete(0, "BalanceLabel");
    ObjectCreate(0, "BalanceLabel", OBJ_LABEL, 0, 0, 0);
    ObjectSetInteger(0, "BalanceLabel", OBJPROP_CORNER, CORNER_RIGHT_LOWER);
    ObjectSetInteger(0, "BalanceLabel", OBJPROP_XDISTANCE, 153);
    ObjectSetInteger(0, "BalanceLabel", OBJPROP_YDISTANCE, 31);
    ObjectSetString(0, "BalanceLabel", OBJPROP_TEXT, "Account BALANCE: " + DoubleToString(accountBalance, 2));
    ObjectSetInteger(0, "BalanceLabel", OBJPROP_FONTSIZE, 16);
    ObjectSetString(0, "BalanceLabel", OBJPROP_FONT, "Times New Roman");
    ObjectSetInteger(0, "BalanceLabel", OBJPROP_COLOR, COLOR_BALANCE_DISPLAY);
    
    // 更新净值显示
    ObjectDelete(0, "EquityLabel");
    ObjectCreate(0, "EquityLabel", OBJ_LABEL, 0, 0, 0);
    ObjectSetInteger(0, "EquityLabel", OBJPROP_CORNER, CORNER_RIGHT_LOWER);
    ObjectSetInteger(0, "EquityLabel", OBJPROP_XDISTANCE, 153);
    ObjectSetInteger(0, "EquityLabel", OBJPROP_YDISTANCE, 11);
    ObjectSetString(0, "EquityLabel", OBJPROP_TEXT, "Account EQUITY: " + DoubleToString(accountEquity, 2));
    ObjectSetInteger(0, "EquityLabel", OBJPROP_FONTSIZE, 16);
    ObjectSetString(0, "EquityLabel", OBJPROP_FONT, "Times New Roman");
    ObjectSetInteger(0, "EquityLabel", OBJPROP_COLOR, equityColor);
}

//+------------------------------------------------------------------+
//| 更新技术指标面板                                                   |
//+------------------------------------------------------------------+
void UpdateTechnicalIndicatorPanel()
{
    // 这里简化技术指标面板的实现
    // 实际实现中应该包含MACD、RSI、CCI等指标的显示
    // 由于篇幅限制，这里只显示基本信息
    
    double currentBid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
    double currentAsk = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
    double currentSpread = (currentAsk - currentBid) / _Point;
    
    ObjectDelete(0, "TechnicalInfo");
    ObjectCreate(0, "TechnicalInfo", OBJ_LABEL, 0, 0, 0);
    ObjectSetInteger(0, "TechnicalInfo", OBJPROP_CORNER, CORNER_LEFT_UPPER);
    ObjectSetInteger(0, "TechnicalInfo", OBJPROP_XDISTANCE, 10);
    ObjectSetInteger(0, "TechnicalInfo", OBJPROP_YDISTANCE, 50);
    ObjectSetString(0, "TechnicalInfo", OBJPROP_TEXT, "Bid: " + DoubleToString(currentBid, _Digits) + " | Ask: " + DoubleToString(currentAsk, _Digits) + " | Spread: " + DoubleToString(currentSpread, 1));
    ObjectSetInteger(0, "TechnicalInfo", OBJPROP_FONTSIZE, 10);
    ObjectSetString(0, "TechnicalInfo", OBJPROP_FONT, "Arial");
    ObjectSetInteger(0, "TechnicalInfo", OBJPROP_COLOR, COLOR_PANEL_TEXT);
}

//+------------------------------------------------------------------+
//| 更新评论区信息显示                                                 |
//+------------------------------------------------------------------+
void UpdateCommentDisplay()
{
    string commentText = "BigGame24.tripod.com\n";
    commentText += "Ilan-TrioKS v1.45 Professional\n";
    commentText += "================================\n";
    commentText += "经纪商: " + AccountInfoString(ACCOUNT_COMPANY) + "\n";
    commentText += "服务器时间: " + TimeToString(TimeCurrent(), TIME_DATE|TIME_SECONDS) + "\n";
    commentText += "================================\n";
    commentText += "账户名称: " + AccountInfoString(ACCOUNT_NAME) + "\n";
    commentText += "账户编号: " + IntegerToString(AccountInfoInteger(ACCOUNT_LOGIN)) + "\n";
    commentText += "账户货币: " + AccountInfoString(ACCOUNT_CURRENCY) + "\n";
    commentText += "===============================\n";
    commentText += "HiLo RSI持仓: " + IntegerToString(GetPositionCount(MAGIC_HILO_RSI)) + "\n";
    commentText += "基础Ilan持仓: " + IntegerToString(GetPositionCount(MAGIC_BASIC_ILAN)) + "\n";
    commentText += "高级Ilan持仓: " + IntegerToString(GetPositionCount(MAGIC_ADVANCED_ILAN)) + "\n";
    commentText += "总持仓数: " + IntegerToString(PositionsTotal()) + "\n";
    commentText += "===============================\n";
    commentText += "账户余额: " + DoubleToString(accountBalance, 2) + "\n";
    commentText += "账户净值: " + DoubleToString(accountEquity, 2) + "\n";
    commentText += "BigGame24.tripod.com";
    
    Comment(commentText);
}

//+------------------------------------------------------------------+
//| HiLo RSI策略执行函数                                              |
//+------------------------------------------------------------------+
void ExecuteHiloRsiStrategy()
{
    // 计算当前手数
    CalculateCurrentLotSize(hiloStrategy.lotSize, UseMoneyManagement, BaseLotSize);
    
    // 应用策略参数
    hiloStrategy.lotSize = (BaseLotSize > MaxLotSize) ? MaxLotSize : BaseLotSize;
    
    // 执行追踪止损
    if (UseTrailingStop)
        ExecuteTrailingStop(MAGIC_HILO_RSI, TrailingStartPoints, TrailingStepPoints);
    
    // 检查超时平仓
    if (HiloUseTimeout)
    {
        if (TimeCurrent() >= hiloStrategy.orderExpiration)
        {
            CloseAllPositions(MAGIC_HILO_RSI);
            Print("HiLo RSI策略：超时平仓执行");
        }
    }
    
    // 检查是否为新K线
    if (hiloStrategy.lastBarTime == iTime(_Symbol, PERIOD_CURRENT, 0))
        return;
    
    hiloStrategy.lastBarTime = iTime(_Symbol, PERIOD_CURRENT, 0);
    
    // 计算当前盈亏
    double currentProfit = CalculateStrategyProfit(MAGIC_HILO_RSI);
    
    // 检查净值止损
    if (UseEquityStop)
    {
        if (currentProfit < 0.0 && MathAbs(currentProfit) > EquityRiskPercent / 100.0 * GetAccountEquityHigh(MAGIC_HILO_RSI))
        {
            CloseAllPositions(MAGIC_HILO_RSI);
            Print("HiLo RSI策略：净值止损执行");
            hiloStrategy.newOrdersPlaced = false;
        }
    }
    
    // 获取当前持仓数
    hiloStrategy.positionCount = GetPositionCount(MAGIC_HILO_RSI);
    
    if (hiloStrategy.positionCount == 0)
    {
        hiloStrategy.isShortTrade = false;
        hiloStrategy.isLongTrade = false;
        hiloStrategy.shouldTradeNow = true;
        hiloStrategy.startEquity = AccountInfoDouble(ACCOUNT_EQUITY);
    }
    
    // 检查持仓方向
    CheckPositionDirection(MAGIC_HILO_RSI, hiloStrategy.isLongTrade, hiloStrategy.isShortTrade);
    
    // 网格交易逻辑
    if (hiloStrategy.positionCount > 0 && hiloStrategy.positionCount <= HiloMaxPositions)
    {
        hiloStrategy.lastBuyPrice = GetLastBuyPrice(MAGIC_HILO_RSI);
        hiloStrategy.lastSellPrice = GetLastSellPrice(MAGIC_HILO_RSI);
        
        double currentAsk = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
        double currentBid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
        
        if (hiloStrategy.isLongTrade && hiloStrategy.lastBuyPrice - currentAsk >= GridStepPoints * _Point)
            hiloStrategy.shouldTradeNow = true;
        
        if (hiloStrategy.isShortTrade && currentBid - hiloStrategy.lastSellPrice >= GridStepPoints * _Point)
            hiloStrategy.shouldTradeNow = true;
    }
    
    // 执行交易
    if (hiloStrategy.shouldTradeNow)
    {
        ExecuteHiloRsiTrade();
    }
    
    // 更新止盈止损
    if (hiloStrategy.newOrdersPlaced)
    {
        UpdateTakeProfitStopLoss(MAGIC_HILO_RSI);
        hiloStrategy.newOrdersPlaced = false;
    }
}

//+------------------------------------------------------------------+
//| 基础Ilan策略执行函数                                              |
//+------------------------------------------------------------------+
void ExecuteBasicIlanStrategy()
{
    // 计算当前手数
    CalculateCurrentLotSize(basicStrategy.lotSize, UseMoneyManagement, BaseLotSize);
    
    // 应用策略参数
    basicStrategy.lotSize = (BaseLotSize > MaxLotSize) ? MaxLotSize : BaseLotSize;
    
    // 执行追踪止损
    if (UseTrailingStop)
        ExecuteTrailingStop(MAGIC_BASIC_ILAN, TrailingStartPoints, TrailingStepPoints);
    
    // 检查是否为新K线（使用策略指定的时间框架）
    ENUM_TIMEFRAMES basicTimeframe = MinutesToTimeframe(basicStrategy.openTimeframe);
    if (basicStrategy.lastBarTime == iTime(_Symbol, basicTimeframe, 0))
        return;
    
    basicStrategy.lastBarTime = iTime(_Symbol, basicTimeframe, 0);
    
    // 计算当前盈亏
    double currentProfit = CalculateStrategyProfit(MAGIC_BASIC_ILAN);
    
    // 检查净值止损
    if (UseEquityStop)
    {
        if (currentProfit < 0.0 && MathAbs(currentProfit) > EquityRiskPercent / 100.0 * GetAccountEquityHigh(MAGIC_BASIC_ILAN))
        {
            CloseAllPositions(MAGIC_BASIC_ILAN);
            Print("基础Ilan策略：净值止损执行");
            basicStrategy.newOrdersPlaced = false;
        }
    }
    
    // 获取当前持仓数
    basicStrategy.positionCount = GetPositionCount(MAGIC_BASIC_ILAN);
    
    if (basicStrategy.positionCount == 0)
    {
        basicStrategy.isShortTrade = false;
        basicStrategy.isLongTrade = false;
        basicStrategy.shouldTradeNow = true;
        basicStrategy.startEquity = AccountInfoDouble(ACCOUNT_EQUITY);
    }
    
    // 检查持仓方向
    CheckPositionDirection(MAGIC_BASIC_ILAN, basicStrategy.isLongTrade, basicStrategy.isShortTrade);
    
    // 网格交易逻辑
    if (basicStrategy.positionCount > 0 && basicStrategy.positionCount <= BasicIlanMaxPositions)
    {
        basicStrategy.lastBuyPrice = GetLastBuyPrice(MAGIC_BASIC_ILAN);
        basicStrategy.lastSellPrice = GetLastSellPrice(MAGIC_BASIC_ILAN);
        
        double currentAsk = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
        double currentBid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
        
        if (basicStrategy.isLongTrade && basicStrategy.lastBuyPrice - currentAsk >= GridStepPoints * _Point)
            basicStrategy.shouldTradeNow = true;
        
        if (basicStrategy.isShortTrade && currentBid - basicStrategy.lastSellPrice >= GridStepPoints * _Point)
            basicStrategy.shouldTradeNow = true;
    }
    
    // 执行交易
    if (basicStrategy.shouldTradeNow)
    {
        ExecuteBasicIlanTrade();
    }
    
    // 更新止盈止损
    if (basicStrategy.newOrdersPlaced)
    {
        UpdateTakeProfitStopLoss(MAGIC_BASIC_ILAN);
        basicStrategy.newOrdersPlaced = false;
    }
}

//+------------------------------------------------------------------+
//| 高级Ilan策略执行函数                                              |
//+------------------------------------------------------------------+
void ExecuteAdvancedIlanStrategy()
{
    // 计算当前手数
    CalculateCurrentLotSize(advancedStrategy.lotSize, UseMoneyManagement, BaseLotSize);
    
    // 应用策略参数
    advancedStrategy.lotSize = (BaseLotSize > MaxLotSize) ? MaxLotSize : BaseLotSize;
    
    // 执行追踪止损
    if (UseTrailingStop)
        ExecuteTrailingStop(MAGIC_ADVANCED_ILAN, TrailingStartPoints, TrailingStepPoints);
    
    // 检查是否为新K线（使用策略指定的时间框架）
    ENUM_TIMEFRAMES advancedTimeframe = MinutesToTimeframe(advancedStrategy.openTimeframe);
    if (advancedStrategy.lastBarTime == iTime(_Symbol, advancedTimeframe, 0))
        return;
    
    advancedStrategy.lastBarTime = iTime(_Symbol, advancedTimeframe, 0);
    
    // 计算当前盈亏
    double currentProfit = CalculateStrategyProfit(MAGIC_ADVANCED_ILAN);
    
    // 检查净值止损
    if (UseEquityStop)
    {
        if (currentProfit < 0.0 && MathAbs(currentProfit) > EquityRiskPercent / 100.0 * GetAccountEquityHigh(MAGIC_ADVANCED_ILAN))
        {
            CloseAllPositions(MAGIC_ADVANCED_ILAN);
            Print("高级Ilan策略：净值止损执行");
            advancedStrategy.newOrdersPlaced = false;
        }
    }
    
    // 获取当前持仓数
    advancedStrategy.positionCount = GetPositionCount(MAGIC_ADVANCED_ILAN);
    
    if (advancedStrategy.positionCount == 0)
    {
        advancedStrategy.isShortTrade = false;
        advancedStrategy.isLongTrade = false;
        advancedStrategy.shouldTradeNow = true;
        advancedStrategy.startEquity = AccountInfoDouble(ACCOUNT_EQUITY);
    }
    
    // 检查持仓方向
    CheckPositionDirection(MAGIC_ADVANCED_ILAN, advancedStrategy.isLongTrade, advancedStrategy.isShortTrade);
    
    // 网格交易逻辑
    if (advancedStrategy.positionCount > 0 && advancedStrategy.positionCount <= AdvancedIlanMaxPositions)
    {
        advancedStrategy.lastBuyPrice = GetLastBuyPrice(MAGIC_ADVANCED_ILAN);
        advancedStrategy.lastSellPrice = GetLastSellPrice(MAGIC_ADVANCED_ILAN);
        
        double currentAsk = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
        double currentBid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
        
        if (advancedStrategy.isLongTrade && advancedStrategy.lastBuyPrice - currentAsk >= GridStepPoints * _Point)
            advancedStrategy.shouldTradeNow = true;
        
        if (advancedStrategy.isShortTrade && currentBid - advancedStrategy.lastSellPrice >= GridStepPoints * _Point)
            advancedStrategy.shouldTradeNow = true;
    }
    
    // 执行交易
    if (advancedStrategy.shouldTradeNow)
    {
        ExecuteAdvancedIlanTrade();
    }
    
    // 更新止盈止损
    if (advancedStrategy.newOrdersPlaced)
    {
        UpdateTakeProfitStopLoss(MAGIC_ADVANCED_ILAN);
        advancedStrategy.newOrdersPlaced = false;
    }
}

//+------------------------------------------------------------------+
//| 工具函数：获取RSI值                                               |
//+------------------------------------------------------------------+
double GetRSIValue(int shift = 1)
{
    // 复制RSI数据到缓冲区
    if (CopyBuffer(rsiHandle, 0, shift, 1, rsiBuffer) <= 0)
    {
        Print("错误：无法复制RSI数据");
        return 50.0; // 返回中性值
    }
    
    return rsiBuffer[0];
}

//+------------------------------------------------------------------+
//| 工具函数：计算当前手数                                             |
//+------------------------------------------------------------------+
void CalculateCurrentLotSize(double &lotSize, bool useMoneyManagement, double baseLotSize)
{
    if (useMoneyManagement)
    {
        if (MathCeil(AccountInfoDouble(ACCOUNT_BALANCE)) < MIN_BALANCE_FOR_MM)
        {
            lotSize = baseLotSize;
        }
        else
        {
            lotSize = MM_COEFFICIENT * MathCeil(AccountInfoDouble(ACCOUNT_BALANCE));
        }
    }
    else
    {
        lotSize = baseLotSize;
    }
}

//+------------------------------------------------------------------+
//| 工具函数：获取指定策略的持仓数量                                     |
//+------------------------------------------------------------------+
int GetPositionCount(int magicNumber)
{
    int count = 0;
    for (int i = PositionsTotal() - 1; i >= 0; i--)
    {
        if (globalPosition.SelectByIndex(i))
        {
            if (globalPosition.Symbol() != _Symbol || globalPosition.Magic() != magicNumber)
                continue;
            
            if (globalPosition.Symbol() == _Symbol && globalPosition.Magic() == magicNumber)
            {
                if (globalPosition.PositionType() == POSITION_TYPE_SELL || globalPosition.PositionType() == POSITION_TYPE_BUY)
                    count++;
            }
        }
    }
    return count;
}

//+------------------------------------------------------------------+
//| 工具函数：检查持仓方向                                             |
//+------------------------------------------------------------------+
void CheckPositionDirection(int magicNumber, bool &isLongTrade, bool &isShortTrade)
{
    for (int i = PositionsTotal() - 1; i >= 0; i--)
    {
        if (globalPosition.SelectByIndex(i))
        {
            if (globalPosition.Symbol() != _Symbol || globalPosition.Magic() != magicNumber)
                continue;
            
            if (globalPosition.Symbol() == _Symbol && globalPosition.Magic() == magicNumber)
            {
                if (globalPosition.PositionType() == POSITION_TYPE_BUY)
                {
                    isLongTrade = true;
                    isShortTrade = false;
                    break;
                }
                if (globalPosition.PositionType() == POSITION_TYPE_SELL)
                {
                    isLongTrade = false;
                    isShortTrade = true;
                    break;
                }
            }
        }
    }
}

//+------------------------------------------------------------------+
//| 工具函数：获取最后买入价格                                         |
//+------------------------------------------------------------------+
double GetLastBuyPrice(int magicNumber)
{
    double lastBuyPrice = 0.0;
    ulong lastTicket = 0;
    
    for (int i = PositionsTotal() - 1; i >= 0; i--)
    {
        if (globalPosition.SelectByIndex(i))
        {
            if (globalPosition.Symbol() != _Symbol || globalPosition.Magic() != magicNumber)
                continue;
            
            if (globalPosition.Symbol() == _Symbol && globalPosition.Magic() == magicNumber && globalPosition.PositionType() == POSITION_TYPE_BUY)
            {
                ulong currentTicket = globalPosition.Ticket();
                if (currentTicket > lastTicket)
                {
                    lastBuyPrice = globalPosition.PriceOpen();
                    lastTicket = currentTicket;
                }
            }
        }
    }
    return lastBuyPrice;
}

//+------------------------------------------------------------------+
//| 工具函数：获取最后卖出价格                                         |
//+------------------------------------------------------------------+
double GetLastSellPrice(int magicNumber)
{
    double lastSellPrice = 0.0;
    ulong lastTicket = 0;
    
    for (int i = PositionsTotal() - 1; i >= 0; i--)
    {
        if (globalPosition.SelectByIndex(i))
        {
            if (globalPosition.Symbol() != _Symbol || globalPosition.Magic() != magicNumber)
                continue;
            
            if (globalPosition.Symbol() == _Symbol && globalPosition.Magic() == magicNumber && globalPosition.PositionType() == POSITION_TYPE_SELL)
            {
                ulong currentTicket = globalPosition.Ticket();
                if (currentTicket > lastTicket)
                {
                    lastSellPrice = globalPosition.PriceOpen();
                    lastTicket = currentTicket;
                }
            }
        }
    }
    return lastSellPrice;
}

//+------------------------------------------------------------------+
//| 工具函数：计算策略盈亏                                             |
//+------------------------------------------------------------------+
double CalculateStrategyProfit(int magicNumber)
{
    double profit = 0.0;
    for (int i = PositionsTotal() - 1; i >= 0; i--)
    {
        if (globalPosition.SelectByIndex(i))
        {
            if (globalPosition.Symbol() != _Symbol || globalPosition.Magic() != magicNumber)
                continue;
            
            if (globalPosition.Symbol() == _Symbol && globalPosition.Magic() == magicNumber)
            {
                if (globalPosition.PositionType() == POSITION_TYPE_BUY || globalPosition.PositionType() == POSITION_TYPE_SELL)
                    profit += globalPosition.Profit();
            }
        }
    }
    return profit;
}

//+------------------------------------------------------------------+
//| 工具函数：关闭指定策略的所有持仓                                     |
//+------------------------------------------------------------------+
void CloseAllPositions(int magicNumber)
{
    for (int i = PositionsTotal() - 1; i >= 0; i--)
    {
        if (globalPosition.SelectByIndex(i))
        {
            if (globalPosition.Symbol() == _Symbol && globalPosition.Magic() == magicNumber)
            {
                if (globalPosition.PositionType() == POSITION_TYPE_BUY)
                {
                    globalTrade.PositionClose(globalPosition.Ticket());
                }
                if (globalPosition.PositionType() == POSITION_TYPE_SELL)
                {
                    globalTrade.PositionClose(globalPosition.Ticket());
                }
                Sleep(1000);
            }
        }
    }
}

//+------------------------------------------------------------------+
//| 工具函数：执行追踪止损                                             |
//+------------------------------------------------------------------+
void ExecuteTrailingStop(int magicNumber, double trailStart, double trailStep)
{
    double averagePrice = CalculateAveragePrice(magicNumber);
    
    if (trailStep == 0) return;
    
    for (int i = PositionsTotal() - 1; i >= 0; i--)
    {
        if (globalPosition.SelectByIndex(i))
        {
            if (globalPosition.Symbol() != _Symbol || globalPosition.Magic() != magicNumber)
                continue;
            
            if (globalPosition.Symbol() == _Symbol && globalPosition.Magic() == magicNumber)
            {
                double currentBid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
                double currentAsk = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
                
                if (globalPosition.PositionType() == POSITION_TYPE_BUY)
                {
                    double profit = NormalizeDouble((currentBid - averagePrice) / _Point, 0);
                    if (profit < trailStart) continue;
                    
                    double currentStopLoss = globalPosition.StopLoss();
                    double newStopLoss = currentBid - trailStep * _Point;
                    
                    if (currentStopLoss == 0.0 || (currentStopLoss != 0.0 && newStopLoss > currentStopLoss))
                    {
                        globalTrade.PositionModify(globalPosition.Ticket(), newStopLoss, globalPosition.TakeProfit());
                    }
                }
                
                if (globalPosition.PositionType() == POSITION_TYPE_SELL)
                {
                    double profit = NormalizeDouble((averagePrice - currentAsk) / _Point, 0);
                    if (profit < trailStart) continue;
                    
                    double currentStopLoss = globalPosition.StopLoss();
                    double newStopLoss = currentAsk + trailStep * _Point;
                    
                    if (currentStopLoss == 0.0 || (currentStopLoss != 0.0 && newStopLoss < currentStopLoss))
                    {
                        globalTrade.PositionModify(globalPosition.Ticket(), newStopLoss, globalPosition.TakeProfit());
                    }
                }
                
                Sleep(1000);
            }
        }
    }
}

//+------------------------------------------------------------------+
//| 工具函数：计算平均价格                                             |
//+------------------------------------------------------------------+
double CalculateAveragePrice(int magicNumber)
{
    double totalPrice = 0.0;
    double totalVolume = 0.0;
    
    for (int i = PositionsTotal() - 1; i >= 0; i--)
    {
        if (globalPosition.SelectByIndex(i))
        {
            if (globalPosition.Symbol() != _Symbol || globalPosition.Magic() != magicNumber)
                continue;
            
            if (globalPosition.Symbol() == _Symbol && globalPosition.Magic() == magicNumber)
            {
                if (globalPosition.PositionType() == POSITION_TYPE_BUY || globalPosition.PositionType() == POSITION_TYPE_SELL)
                {
                    totalPrice += globalPosition.PriceOpen() * globalPosition.Volume();
                    totalVolume += globalPosition.Volume();
                }
            }
        }
    }
    
    if (totalVolume > 0)
        return NormalizeDouble(totalPrice / totalVolume, _Digits);
    else
        return 0.0;
}

//+------------------------------------------------------------------+
//| 工具函数：获取账户净值最高点                                       |
//+------------------------------------------------------------------+
double GetAccountEquityHigh(int magicNumber)
{
    static double hiloEquityHigh = 0.0;
    static double basicEquityHigh = 0.0;
    static double advancedEquityHigh = 0.0;
    static double hiloPrevEquity = 0.0;
    static double basicPrevEquity = 0.0;
    static double advancedPrevEquity = 0.0;
    
    double currentEquity = AccountInfoDouble(ACCOUNT_EQUITY);
    
    if (magicNumber == MAGIC_HILO_RSI)
    {
        if (GetPositionCount(MAGIC_HILO_RSI) == 0)
            hiloEquityHigh = currentEquity;
        
        if (hiloEquityHigh < hiloPrevEquity)
            hiloEquityHigh = hiloPrevEquity;
        else
            hiloEquityHigh = currentEquity;
        
        hiloPrevEquity = currentEquity;
        return hiloEquityHigh;
    }
    else if (magicNumber == MAGIC_BASIC_ILAN)
    {
        if (GetPositionCount(MAGIC_BASIC_ILAN) == 0)
            basicEquityHigh = currentEquity;
        
        if (basicEquityHigh < basicPrevEquity)
            basicEquityHigh = basicPrevEquity;
        else
            basicEquityHigh = currentEquity;
        
        basicPrevEquity = currentEquity;
        return basicEquityHigh;
    }
    else if (magicNumber == MAGIC_ADVANCED_ILAN)
    {
        if (GetPositionCount(MAGIC_ADVANCED_ILAN) == 0)
            advancedEquityHigh = currentEquity;
        
        if (advancedEquityHigh < advancedPrevEquity)
            advancedEquityHigh = advancedPrevEquity;
        else
            advancedEquityHigh = currentEquity;
        
        advancedPrevEquity = currentEquity;
        return advancedEquityHigh;
    }
    
    return currentEquity;
}

//+------------------------------------------------------------------+
//| 工具函数：更新止盈止损                                             |
//+------------------------------------------------------------------+
void UpdateTakeProfitStopLoss(int magicNumber)
{
    double averagePrice = CalculateAveragePrice(magicNumber);
    if (averagePrice == 0.0) return;
    
    double takeProfitPrice = 0.0;
    double stopLossPrice = 0.0;
    bool hasLongPosition = false;
    bool hasShortPosition = false;
    
    // 检查持仓方向
    for (int i = PositionsTotal() - 1; i >= 0; i--)
    {
        if (globalPosition.SelectByIndex(i))
        {
            if (globalPosition.Symbol() != _Symbol || globalPosition.Magic() != magicNumber)
                continue;
            
            if (globalPosition.Symbol() == _Symbol && globalPosition.Magic() == magicNumber)
            {
                if (globalPosition.PositionType() == POSITION_TYPE_BUY)
                {
                    hasLongPosition = true;
                    takeProfitPrice = averagePrice + TakeProfitPoints * _Point;
                    stopLossPrice = averagePrice - HiloStopLossPoints * _Point;
                    break;
                }
                if (globalPosition.PositionType() == POSITION_TYPE_SELL)
                {
                    hasShortPosition = true;
                    takeProfitPrice = averagePrice - TakeProfitPoints * _Point;
                    stopLossPrice = averagePrice + HiloStopLossPoints * _Point;
                    break;
                }
            }
        }
    }
    
    // 更新所有相关持仓的止盈止损
    if (hasLongPosition || hasShortPosition)
    {
        for (int i = PositionsTotal() - 1; i >= 0; i--)
        {
            if (globalPosition.SelectByIndex(i))
            {
                if (globalPosition.Symbol() != _Symbol || globalPosition.Magic() != magicNumber)
                    continue;
                
                if (globalPosition.Symbol() == _Symbol && globalPosition.Magic() == magicNumber)
                {
                    // 使用重试机制修改订单
                    bool modifySuccess = false;
                    for (int attempts = 0; attempts < MAX_RETRY_COUNT && !modifySuccess; attempts++)
                    {
                        if (globalTrade.PositionModify(globalPosition.Ticket(), globalPosition.StopLoss(), takeProfitPrice))
                        {
                            modifySuccess = true;
                            Print("订单修改成功 - 票据: ", globalPosition.Ticket(), " 止盈: ", takeProfitPrice);
                        }
                        else
                        {
                            Print("订单修改重试 ", attempts + 1, "/", MAX_RETRY_COUNT, " - 票据: ", globalPosition.Ticket());
                            Sleep(1000);
                            // MQL5中价格自动更新，无需手动刷新
                        }
                    }
                    
                    if (!modifySuccess)
                    {
                        Print("警告：订单修改失败 - 票据: ", globalPosition.Ticket());
                    }
                }
            }
        }
    }
}

//+------------------------------------------------------------------+
//| HiLo RSI策略具体交易执行                                          |
//+------------------------------------------------------------------+
void ExecuteHiloRsiTrade()
{
    // 获取RSI值进行过滤
    double rsiValue = GetRSIValue(1);
    
    // 获取高低点进行判断（与MQ4逻辑完全一致）
    double previousHigh = iHigh(_Symbol, PERIOD_CURRENT, 1);  // 前一根K线的高点
    double previousLow = iLow(_Symbol, PERIOD_CURRENT, 2);    // 第二根K线的低点
    
    double currentBid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
    double currentAsk = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
    
    // 计算手数
    hiloStrategy.currentLotSize = NormalizeDouble(hiloStrategy.lotSize * MathPow(hiloStrategy.lotMultiplier, hiloStrategy.positionCount), hiloStrategy.lotDecimalPlaces);
    
    // HiLo RSI交易逻辑 
    // 
    if (hiloStrategy.positionCount < 1)
    {
        //上一根K线的高点要高于 上上根K线的低点  行情上涨或者下跌时反弹 ，绝大多数情况
        if (previousHigh > previousLow)  
        {
            // 高点突破，考虑卖出（需要RSI确认）
            if (rsiValue > 30.0)
            {
                if (ExecuteMarketOrder(ORDER_TYPE_SELL, hiloStrategy.currentLotSize, currentBid, SlippagePoints, 0, 0, "HiLo-RSI-" + IntegerToString(hiloStrategy.tradeNumber), MAGIC_HILO_RSI, COLOR_SELL_SIGNAL))
                {
                    hiloStrategy.newOrdersPlaced = true;
                    hiloStrategy.orderExpiration = TimeCurrent() + (ulong)(60 * 60 * HiloTimeoutHours);
                    Print("HiLo RSI策略：执行卖出交易");
                }
            }
        }
        else   //行情
        {
            // 低点突破，考虑买入（需要RSI确认）
            if (rsiValue < 70.0)
            {
                if (ExecuteMarketOrder(ORDER_TYPE_BUY, hiloStrategy.currentLotSize, currentAsk, SlippagePoints, 0, 0, "HiLo-RSI-" + IntegerToString(hiloStrategy.tradeNumber), MAGIC_HILO_RSI, COLOR_BUY_SIGNAL))
                {
                    hiloStrategy.newOrdersPlaced = true;
                    hiloStrategy.orderExpiration = TimeCurrent() + (ulong)(60 * 60 * HiloTimeoutHours);
                    Print("HiLo RSI策略：执行买入交易");
                }
            }
        }
    }
    else
    {
        // 网格交易逻辑
        if (hiloStrategy.isShortTrade)
        {
            if (ExecuteMarketOrder(ORDER_TYPE_SELL, hiloStrategy.currentLotSize, currentBid, SlippagePoints, 0, 0, "HiLo-RSI-" + IntegerToString(hiloStrategy.tradeNumber), MAGIC_HILO_RSI, COLOR_SELL_SIGNAL))
            {
                hiloStrategy.newOrdersPlaced = true;
                Print("HiLo RSI策略：执行网格卖出交易");
            }
        }
        else if (hiloStrategy.isLongTrade)
        {
            if (ExecuteMarketOrder(ORDER_TYPE_BUY, hiloStrategy.currentLotSize, currentAsk, SlippagePoints, 0, 0, "HiLo-RSI-" + IntegerToString(hiloStrategy.tradeNumber), MAGIC_HILO_RSI, COLOR_BUY_SIGNAL))
            {
                hiloStrategy.newOrdersPlaced = true;
                Print("HiLo RSI策略：执行网格买入交易");
            }
        }
    }
    
    hiloStrategy.shouldTradeNow = false;
}

//+------------------------------------------------------------------+
//| 基础Ilan策略具体交易执行                                          |
//+------------------------------------------------------------------+
void ExecuteBasicIlanTrade()
{
    // 获取价格比较数据
    double previousClose = iClose(_Symbol, PERIOD_CURRENT, 2);
    double currentClose = iClose(_Symbol, PERIOD_CURRENT, 1);
    
    double currentBid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
    double currentAsk = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
    
    // 计算手数
    basicStrategy.currentLotSize = NormalizeDouble(basicStrategy.lotSize * MathPow(basicStrategy.lotMultiplier, basicStrategy.positionCount), basicStrategy.lotDecimalPlaces);
    
    // 基础Ilan交易逻辑
    if (basicStrategy.positionCount < 1)
    {
        if (previousClose > currentClose)
        {
            // 价格下跌，考虑卖出
            if (ExecuteMarketOrder(ORDER_TYPE_SELL, basicStrategy.currentLotSize, currentBid, SlippagePoints, 0, 0, "Basic-Ilan-" + IntegerToString(basicStrategy.tradeNumber), MAGIC_BASIC_ILAN, COLOR_SELL_SIGNAL))
            {
                basicStrategy.newOrdersPlaced = true;
                Print("基础Ilan策略：执行卖出交易");
            }
        }
        else
        {
            // 价格上涨，考虑买入
            if (ExecuteMarketOrder(ORDER_TYPE_BUY, basicStrategy.currentLotSize, currentAsk, SlippagePoints, 0, 0, "Basic-Ilan-" + IntegerToString(basicStrategy.tradeNumber), MAGIC_BASIC_ILAN, COLOR_BUY_SIGNAL))
            {
                basicStrategy.newOrdersPlaced = true;
                Print("基础Ilan策略：执行买入交易");
            }
        }
    }
    else
    {
        // 网格交易逻辑
        if (basicStrategy.isShortTrade)
        {
            if (ExecuteMarketOrder(ORDER_TYPE_SELL, basicStrategy.currentLotSize, currentBid, SlippagePoints, 0, 0, "Basic-Ilan-" + IntegerToString(basicStrategy.tradeNumber), MAGIC_BASIC_ILAN, COLOR_SELL_SIGNAL))
            {
                basicStrategy.newOrdersPlaced = true;
                Print("基础Ilan策略：执行网格卖出交易");
            }
        }
        else if (basicStrategy.isLongTrade)
        {
            if (ExecuteMarketOrder(ORDER_TYPE_BUY, basicStrategy.currentLotSize, currentAsk, SlippagePoints, 0, 0, "Basic-Ilan-" + IntegerToString(basicStrategy.tradeNumber), MAGIC_BASIC_ILAN, COLOR_BUY_SIGNAL))
            {
                basicStrategy.newOrdersPlaced = true;
                Print("基础Ilan策略：执行网格买入交易");
            }
        }
    }
    
    basicStrategy.shouldTradeNow = false;
}

//+------------------------------------------------------------------+
//| 高级Ilan策略具体交易执行                                          |
//+------------------------------------------------------------------+
void ExecuteAdvancedIlanTrade()
{
    // 获取价格比较数据
    double previousClose = iClose(_Symbol, PERIOD_CURRENT, 2);
    double currentClose = iClose(_Symbol, PERIOD_CURRENT, 1);
    
    // 获取RSI值进行过滤
    double rsiValue = GetRSIValue(1);
    
    double currentBid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
    double currentAsk = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
    
    // 计算手数
    advancedStrategy.currentLotSize = NormalizeDouble(advancedStrategy.lotSize * MathPow(advancedStrategy.lotMultiplier, advancedStrategy.positionCount), advancedStrategy.lotDecimalPlaces);
    
    // 高级Ilan交易逻辑（带RSI过滤）
    if (advancedStrategy.positionCount < 1)
    {
        if (previousClose > currentClose)
        {
            // 价格下跌，考虑卖出（需要RSI确认）
            if (rsiValue > 30.0)
            {
                if (ExecuteMarketOrder(ORDER_TYPE_SELL, advancedStrategy.currentLotSize, currentBid, SlippagePoints, 0, 0, "Advanced-Ilan-" + IntegerToString(advancedStrategy.tradeNumber), MAGIC_ADVANCED_ILAN, COLOR_SELL_SIGNAL))
                {
                    advancedStrategy.newOrdersPlaced = true;
                    Print("高级Ilan策略：执行卖出交易");
                }
            }
        }
        else
        {
            // 价格上涨，考虑买入（需要RSI确认）
            if (rsiValue < 70.0)
            {
                if (ExecuteMarketOrder(ORDER_TYPE_BUY, advancedStrategy.currentLotSize, currentAsk, SlippagePoints, 0, 0, "Advanced-Ilan-" + IntegerToString(advancedStrategy.tradeNumber), MAGIC_ADVANCED_ILAN, COLOR_BUY_SIGNAL))
                {
                    advancedStrategy.newOrdersPlaced = true;
                    Print("高级Ilan策略：执行买入交易");
                }
            }
        }
    }
    else
    {
        // 网格交易逻辑
        if (advancedStrategy.isShortTrade)
        {
            if (ExecuteMarketOrder(ORDER_TYPE_SELL, advancedStrategy.currentLotSize, currentBid, SlippagePoints, 0, 0, "Advanced-Ilan-" + IntegerToString(advancedStrategy.tradeNumber), MAGIC_ADVANCED_ILAN, COLOR_SELL_SIGNAL))
            {
                advancedStrategy.newOrdersPlaced = true;
                Print("高级Ilan策略：执行网格卖出交易");
            }
        }
        else if (advancedStrategy.isLongTrade)
        {
            if (ExecuteMarketOrder(ORDER_TYPE_BUY, advancedStrategy.currentLotSize, currentAsk, SlippagePoints, 0, 0, "Advanced-Ilan-" + IntegerToString(advancedStrategy.tradeNumber), MAGIC_ADVANCED_ILAN, COLOR_BUY_SIGNAL))
            {
                advancedStrategy.newOrdersPlaced = true;
                Print("高级Ilan策略：执行网格买入交易");
            }
        }
    }
    
    advancedStrategy.shouldTradeNow = false;
}

//+------------------------------------------------------------------+
//| 核心工具函数：执行市价单                                           |
//+------------------------------------------------------------------+
bool ExecuteMarketOrder(ENUM_ORDER_TYPE orderType, double lotSize, double price, double slippage, double stopLoss, double takeProfit, string comment, int magicNumber, color orderColor)
{
    // 重试机制
    for (int attempts = 0; attempts < MAX_RETRY_COUNT; attempts++)
    {
        MqlTradeRequest request = {};
        MqlTradeResult result = {};
        
        request.action = TRADE_ACTION_DEAL;
        request.symbol = _Symbol;
        request.volume = lotSize;
        request.type = orderType;
        request.price = price;
        request.sl = stopLoss;
        request.tp = takeProfit;
        request.deviation = (ulong)slippage;
        request.magic = magicNumber;
        request.comment = comment;
        request.type_filling = ORDER_FILLING_FOK;
        
        if (OrderSend(request, result))
        {
            if (result.retcode == TRADE_RETCODE_DONE)
            {
                Print("交易成功执行 - 订单号: ", result.order, " 策略: ", comment);
                return true;
            }
        }
        
        // 检查是否需要重试
        if (result.retcode != TRADE_RETCODE_REQUOTE && 
            result.retcode != TRADE_RETCODE_TIMEOUT && 
            result.retcode != TRADE_RETCODE_PRICE_OFF)
        {
            Print("交易失败，错误代码: ", result.retcode, " 描述: ", result.comment);
            break;
        }
        
        Print("交易重试 ", attempts + 1, "/", MAX_RETRY_COUNT, " - 错误: ", result.retcode);
        Sleep(RETRY_DELAY_MS);
    }
    
    return false;
}

//+------------------------------------------------------------------+
//| 工具函数：计算多头止损价格                                         |
//+------------------------------------------------------------------+
double CalculateStopLossLong(double price, double stopPoints)
{
    if (stopPoints == 0) return 0.0;
    return price - stopPoints * _Point;
}

//+------------------------------------------------------------------+
//| 工具函数：计算空头止损价格                                         |
//+------------------------------------------------------------------+
double CalculateStopLossShort(double price, double stopPoints)
{
    if (stopPoints == 0) return 0.0;
    return price + stopPoints * _Point;
}

//+------------------------------------------------------------------+
//| 工具函数：计算多头止盈价格                                         |
//+------------------------------------------------------------------+
double CalculateTakeProfitLong(double price, double profitPoints)
{
    if (profitPoints == 0) return 0.0;
    return price + profitPoints * _Point;
}

//+------------------------------------------------------------------+
//| 工具函数：计算空头止盈价格                                         |
//+------------------------------------------------------------------+
double CalculateTakeProfitShort(double price, double profitPoints)
{
    if (profitPoints == 0) return 0.0;
    return price - profitPoints * _Point;
}

//+------------------------------------------------------------------+
//| 完整的技术指标面板更新函数                                         |
//+------------------------------------------------------------------+
void UpdateCompleteTechnicalPanel()
{
    // 清理现有指标面板
    for (int i = 0; i < 7; i++)
    {
        ObjectDelete(0, "TF_Label_" + IntegerToString(i));
        ObjectDelete(0, "MACD_Signal_" + IntegerToString(i));
        ObjectDelete(0, "STR_Signal_" + IntegerToString(i));
        ObjectDelete(0, "EMA_Signal_" + IntegerToString(i));
    }
    
    // 获取当前报价
    double currentBid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
    double currentAsk = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
    double currentSpread = (currentAsk - currentBid) / _Point;
    
    // 创建时间框架标签
    string timeframeLabels[] = {"M1", "M5", "M15", "M30", "H1", "H4", "D1"};
    ENUM_TIMEFRAMES timeframes[] = {PERIOD_M1, PERIOD_M5, PERIOD_M15, PERIOD_M30, PERIOD_H1, PERIOD_H4, PERIOD_D1};
    
    for (int i = 0; i < 7; i++)
    {
        // 创建时间框架标签
        ObjectCreate(0, "TF_Label_" + IntegerToString(i), OBJ_LABEL, 0, 0, 0);
        ObjectSetInteger(0, "TF_Label_" + IntegerToString(i), OBJPROP_CORNER, CORNER_LEFT_UPPER);
        ObjectSetInteger(0, "TF_Label_" + IntegerToString(i), OBJPROP_XDISTANCE, 10 + i * 20);
        ObjectSetInteger(0, "TF_Label_" + IntegerToString(i), OBJPROP_YDISTANCE, 80);
        ObjectSetString(0, "TF_Label_" + IntegerToString(i), OBJPROP_TEXT, timeframeLabels[i]);
        ObjectSetInteger(0, "TF_Label_" + IntegerToString(i), OBJPROP_FONTSIZE, 7);
        ObjectSetString(0, "TF_Label_" + IntegerToString(i), OBJPROP_FONT, "Arial Bold");
        ObjectSetInteger(0, "TF_Label_" + IntegerToString(i), OBJPROP_COLOR, clrGray);
        
        // 计算MACD信号
        double macdMain = 0.0;
        double macdSignal = 0.0;
        
        if (macdHandles[i] != INVALID_HANDLE)
        {
            if (CopyBuffer(macdHandles[i], 0, 0, 1, macdMainBuffer) > 0)
                macdMain = macdMainBuffer[0];
            if (CopyBuffer(macdHandles[i], 1, 0, 1, macdSignalBuffer) > 0)
                macdSignal = macdSignalBuffer[0];
        }
        
        color macdColor = clrGray;
        if (macdMain > macdSignal && macdMain > 0.0) macdColor = clrLime;
        else if (macdMain <= macdSignal && macdMain < 0.0) macdColor = clrRed;
        else if (macdMain > macdSignal) macdColor = clrGreen;
        else macdColor = clrOrange;
        
        ObjectCreate(0, "MACD_Signal_" + IntegerToString(i), OBJ_LABEL, 0, 0, 0);
        ObjectSetInteger(0, "MACD_Signal_" + IntegerToString(i), OBJPROP_CORNER, CORNER_LEFT_UPPER);
        ObjectSetInteger(0, "MACD_Signal_" + IntegerToString(i), OBJPROP_XDISTANCE, 10 + i * 20);
        ObjectSetInteger(0, "MACD_Signal_" + IntegerToString(i), OBJPROP_YDISTANCE, 90);
        ObjectSetString(0, "MACD_Signal_" + IntegerToString(i), OBJPROP_TEXT, "●");
        ObjectSetInteger(0, "MACD_Signal_" + IntegerToString(i), OBJPROP_FONTSIZE, 12);
        ObjectSetString(0, "MACD_Signal_" + IntegerToString(i), OBJPROP_FONT, "Arial");
        ObjectSetInteger(0, "MACD_Signal_" + IntegerToString(i), OBJPROP_COLOR, macdColor);
        
        // 计算STR信号（RSI + CCI + Stochastic组合）
        double rsiValue = 50.0;
        double cciValue = 0.0;
        double stochValue = 50.0;
        
        if (rsiHandles[i] != INVALID_HANDLE)
        {
            if (CopyBuffer(rsiHandles[i], 0, 0, 1, rsiTempBuffer) > 0)
                rsiValue = rsiTempBuffer[0];
        }
        
        if (cciHandles[i] != INVALID_HANDLE)
        {
            if (CopyBuffer(cciHandles[i], 0, 0, 1, cciTempBuffer) > 0)
                cciValue = cciTempBuffer[0];
        }
        
        if (stochHandles[i] != INVALID_HANDLE)
        {
            if (CopyBuffer(stochHandles[i], 0, 0, 1, stochTempBuffer) > 0)
                stochValue = stochTempBuffer[0];
        }
        
        color strColor = clrGray;
        if (rsiValue > 50.0 && stochValue > 40.0 && cciValue > 0.0) strColor = clrLime;
        else if (rsiValue < 50.0 && stochValue < 60.0 && cciValue < 0.0) strColor = clrRed;
        else strColor = clrYellow;
        
        ObjectCreate(0, "STR_Signal_" + IntegerToString(i), OBJ_LABEL, 0, 0, 0);
        ObjectSetInteger(0, "STR_Signal_" + IntegerToString(i), OBJPROP_CORNER, CORNER_LEFT_UPPER);
        ObjectSetInteger(0, "STR_Signal_" + IntegerToString(i), OBJPROP_XDISTANCE, 10 + i * 20);
        ObjectSetInteger(0, "STR_Signal_" + IntegerToString(i), OBJPROP_YDISTANCE, 105);
        ObjectSetString(0, "STR_Signal_" + IntegerToString(i), OBJPROP_TEXT, "●");
        ObjectSetInteger(0, "STR_Signal_" + IntegerToString(i), OBJPROP_FONTSIZE, 12);
        ObjectSetString(0, "STR_Signal_" + IntegerToString(i), OBJPROP_FONT, "Arial");
        ObjectSetInteger(0, "STR_Signal_" + IntegerToString(i), OBJPROP_COLOR, strColor);
        
        // 计算EMA信号
        double emaFast = 0.0;
        double emaSlow = 0.0;
        
        if (maFastHandles[i] != INVALID_HANDLE)
        {
            if (CopyBuffer(maFastHandles[i], 0, 0, 1, maFastBuffer) > 0)
                emaFast = maFastBuffer[0];
        }
        
        if (maSlowHandles[i] != INVALID_HANDLE)
        {
            if (CopyBuffer(maSlowHandles[i], 0, 0, 1, maSlowBuffer) > 0)
                emaSlow = maSlowBuffer[0];
        }
        
        color emaColor = (emaFast > emaSlow) ? clrLime : clrRed;
        
        ObjectCreate(0, "EMA_Signal_" + IntegerToString(i), OBJ_LABEL, 0, 0, 0);
        ObjectSetInteger(0, "EMA_Signal_" + IntegerToString(i), OBJPROP_CORNER, CORNER_LEFT_UPPER);
        ObjectSetInteger(0, "EMA_Signal_" + IntegerToString(i), OBJPROP_XDISTANCE, 10 + i * 20);
        ObjectSetInteger(0, "EMA_Signal_" + IntegerToString(i), OBJPROP_YDISTANCE, 120);
        ObjectSetString(0, "EMA_Signal_" + IntegerToString(i), OBJPROP_TEXT, "●");
        ObjectSetInteger(0, "EMA_Signal_" + IntegerToString(i), OBJPROP_FONTSIZE, 12);
        ObjectSetString(0, "EMA_Signal_" + IntegerToString(i), OBJPROP_FONT, "Arial");
        ObjectSetInteger(0, "EMA_Signal_" + IntegerToString(i), OBJPROP_COLOR, emaColor);
    }
    
    // 创建指标说明标签
    ObjectCreate(0, "MACD_Label", OBJ_LABEL, 0, 0, 0);
    ObjectSetInteger(0, "MACD_Label", OBJPROP_CORNER, CORNER_LEFT_UPPER);
    ObjectSetInteger(0, "MACD_Label", OBJPROP_XDISTANCE, 160);
    ObjectSetInteger(0, "MACD_Label", OBJPROP_YDISTANCE, 90);
    ObjectSetString(0, "MACD_Label", OBJPROP_TEXT, "MACD");
    ObjectSetInteger(0, "MACD_Label", OBJPROP_FONTSIZE, 8);
    ObjectSetString(0, "MACD_Label", OBJPROP_FONT, "Arial");
    ObjectSetInteger(0, "MACD_Label", OBJPROP_COLOR, clrGray);
    
    ObjectCreate(0, "STR_Label", OBJ_LABEL, 0, 0, 0);
    ObjectSetInteger(0, "STR_Label", OBJPROP_CORNER, CORNER_LEFT_UPPER);
    ObjectSetInteger(0, "STR_Label", OBJPROP_XDISTANCE, 160);
    ObjectSetInteger(0, "STR_Label", OBJPROP_YDISTANCE, 105);
    ObjectSetString(0, "STR_Label", OBJPROP_TEXT, "STR");
    ObjectSetInteger(0, "STR_Label", OBJPROP_FONTSIZE, 8);
    ObjectSetString(0, "STR_Label", OBJPROP_FONT, "Arial");
    ObjectSetInteger(0, "STR_Label", OBJPROP_COLOR, clrGray);
    
    ObjectCreate(0, "EMA_Label", OBJ_LABEL, 0, 0, 0);
    ObjectSetInteger(0, "EMA_Label", OBJPROP_CORNER, CORNER_LEFT_UPPER);
    ObjectSetInteger(0, "EMA_Label", OBJPROP_XDISTANCE, 160);
    ObjectSetInteger(0, "EMA_Label", OBJPROP_YDISTANCE, 120);
    ObjectSetString(0, "EMA_Label", OBJPROP_TEXT, "EMA");
    ObjectSetInteger(0, "EMA_Label", OBJPROP_FONTSIZE, 8);
    ObjectSetString(0, "EMA_Label", OBJPROP_FONT, "Arial");
    ObjectSetInteger(0, "EMA_Label", OBJPROP_COLOR, clrGray);
    
    // 显示当前价格和点差信息
    ObjectCreate(0, "Price_Info", OBJ_LABEL, 0, 0, 0);
    ObjectSetInteger(0, "Price_Info", OBJPROP_CORNER, CORNER_LEFT_UPPER);
    ObjectSetInteger(0, "Price_Info", OBJPROP_XDISTANCE, 10);
    ObjectSetInteger(0, "Price_Info", OBJPROP_YDISTANCE, 140);
    ObjectSetString(0, "Price_Info", OBJPROP_TEXT, "Price: " + DoubleToString(currentBid, _Digits) + " | Spread: " + DoubleToString(currentSpread, 1));
    ObjectSetInteger(0, "Price_Info", OBJPROP_FONTSIZE, 10);
    ObjectSetString(0, "Price_Info", OBJPROP_FONT, "Arial");
    ObjectSetInteger(0, "Price_Info", OBJPROP_COLOR, clrWhite);
    
    // 显示波动率信息
    int dailyRange = (int)((iHigh(_Symbol, PERIOD_D1, 1) - iLow(_Symbol, PERIOD_D1, 1)) / _Point);
    int currentDailyRange = (int)((iHigh(_Symbol, PERIOD_D1, 0) - iLow(_Symbol, PERIOD_D1, 0)) / _Point);
    
    ObjectCreate(0, "Volatility_Info", OBJ_LABEL, 0, 0, 0);
    ObjectSetInteger(0, "Volatility_Info", OBJPROP_CORNER, CORNER_LEFT_UPPER);
    ObjectSetInteger(0, "Volatility_Info", OBJPROP_XDISTANCE, 10);
    ObjectSetInteger(0, "Volatility_Info", OBJPROP_YDISTANCE, 155);
    ObjectSetString(0, "Volatility_Info", OBJPROP_TEXT, "Daily Range: " + IntegerToString(currentDailyRange) + " | Prev: " + IntegerToString(dailyRange));
    ObjectSetInteger(0, "Volatility_Info", OBJPROP_FONTSIZE, 10);
    ObjectSetString(0, "Volatility_Info", OBJPROP_FONT, "Arial");
    ObjectSetInteger(0, "Volatility_Info", OBJPROP_COLOR, clrGold);
}

//+------------------------------------------------------------------+
//| 工具函数：将分钟数转换为时间框架枚举                                 |
//+------------------------------------------------------------------+
ENUM_TIMEFRAMES MinutesToTimeframe(int minutes)
{
    switch (minutes)
    {
        case 1: return PERIOD_M1;
        case 5: return PERIOD_M5;
        case 15: return PERIOD_M15;
        case 30: return PERIOD_M30;
        case 60: return PERIOD_H1;
        case 240: return PERIOD_H4;
        case 1440: return PERIOD_D1;
        case 10080: return PERIOD_W1;
        case 43200: return PERIOD_MN1;
        default: return PERIOD_CURRENT;
    }
}

//+------------------------------------------------------------------+
//| 工具函数：检查指定时间框架是否有新K线                               |
//+------------------------------------------------------------------+
bool IsNewTimeframe(ENUM_TIMEFRAMES timeframe, datetime &lastTime)
{
    datetime currentTime = iTime(_Symbol, timeframe, 0);
    if (lastTime != currentTime)
    {
        lastTime = currentTime;
        return true;
    }
    return false;
}

//+------------------------------------------------------------------+
//| 工具函数：获取策略描述                                             |
//+------------------------------------------------------------------+
string GetStrategyDescription(int magicNumber)
{
    switch (magicNumber)
    {
        case MAGIC_HILO_RSI:
            return "HiLo RSI策略";
        case MAGIC_BASIC_ILAN:
            return "基础Ilan策略";
        case MAGIC_ADVANCED_ILAN:
            return "高级Ilan策略";
        default:
            return "未知策略";
    }
}

//+------------------------------------------------------------------+
//| 工具函数：格式化持仓信息                                           |
//+------------------------------------------------------------------+
string FormatPositionInfo(int magicNumber)
{
    int positionCount = GetPositionCount(magicNumber);
    double totalProfit = CalculateStrategyProfit(magicNumber);
    double totalVolume = 0.0;
    
    for (int i = PositionsTotal() - 1; i >= 0; i--)
    {
        if (globalPosition.SelectByIndex(i))
        {
            if (globalPosition.Symbol() == _Symbol && globalPosition.Magic() == magicNumber)
            {
                totalVolume += globalPosition.Volume();
            }
        }
    }
    
    string info = GetStrategyDescription(magicNumber) + ": ";
    info += "持仓=" + IntegerToString(positionCount);
    info += " | 手数=" + DoubleToString(totalVolume, 2);
    info += " | 盈亏=" + DoubleToString(totalProfit, 2);
    
    return info;
}

//+------------------------------------------------------------------+
//| 工具函数：清理过期的界面元素                                       |
//+------------------------------------------------------------------+
void CleanupExpiredObjects()
{
    // 清理技术指标面板相关对象
    for (int i = 0; i < 20; i++)
    {
        ObjectDelete(0, "TF_Label_" + IntegerToString(i));
        ObjectDelete(0, "MACD_Signal_" + IntegerToString(i));
        ObjectDelete(0, "STR_Signal_" + IntegerToString(i));
        ObjectDelete(0, "EMA_Signal_" + IntegerToString(i));
    }
    
    // 清理其他可能的对象
    ObjectDelete(0, "MACD_Label");
    ObjectDelete(0, "STR_Label");
    ObjectDelete(0, "EMA_Label");
    ObjectDelete(0, "Price_Info");
    ObjectDelete(0, "Volatility_Info");
    ObjectDelete(0, "TechnicalInfo");
}

//+------------------------------------------------------------------+
//| 工具函数：记录交易统计信息                                         |
//+------------------------------------------------------------------+
void LogTradingStatistics()
{
    string statsInfo = "=== 交易统计信息 ===\n";
    statsInfo += FormatPositionInfo(MAGIC_HILO_RSI) + "\n";
    statsInfo += FormatPositionInfo(MAGIC_BASIC_ILAN) + "\n";
    statsInfo += FormatPositionInfo(MAGIC_ADVANCED_ILAN) + "\n";
    statsInfo += "总持仓数: " + IntegerToString(PositionsTotal()) + "\n";
    statsInfo += "账户余额: " + DoubleToString(AccountInfoDouble(ACCOUNT_BALANCE), 2) + "\n";
    statsInfo += "账户净值: " + DoubleToString(AccountInfoDouble(ACCOUNT_EQUITY), 2) + "\n";
    statsInfo += "==================";
    
    Print(statsInfo);
}

//+------------------------------------------------------------------+
//| 结束标记                                                          |
//+------------------------------------------------------------------+